import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { SpiderService } from './spider.service';
import { CreateSpiderDto } from './dto/create-spider.dto';
import { UpdateSpiderDto } from './dto/update-spider.dto';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { join } from 'path';

import * as fs from 'fs';
import { ApiTags } from '@nestjs/swagger';
@Controller('spider')
@ApiTags('spider模块')
export class SpiderController {
  constructor(private readonly spiderService: SpiderService) {}

  @Post()
  create(@Body() createSpiderDto: CreateSpiderDto) {
    return this.spiderService.create(createSpiderDto);
  }

  @Get()
  async findAll() {
    const baseUrl = 'http:/xxx/';
    // http:/xxx/index_2.htm
    let index = 0;
    const urls: string[] = [];
    const getCosPlay = async () => {
      const pageUrl = index == 0 ? '' : `index_${index}.htm`;
      await axios
        .get(`${baseUrl}/${index ? '' : pageUrl}`)
        .then(async (res) => {
          const $ = cheerio.load(res.data);
          const page = $('.page a')
            .map(function () {
              return $(this).text();
            })
            .toArray();
          console.log('page', page);
          if (index <= 1) {
            //2页
            $('a img').each(function () {
              // console.log('a img', $(this).attr('src'));
              urls.push($(this).attr('src'));
            });
            index++;
            await getCosPlay();
          }
        });
    };
    await getCosPlay();
    this.writeFile(urls);
    console.log('urls', urls);
    return this.spiderService.findAll() + urls;
  }
  writeFile(urls: string[]) {
    urls.forEach(async (url) => {
      const buffer = await axios
        .get(url, { responseType: 'arraybuffer' })
        .then((res) => res.data);
      const ws = fs.createWriteStream(
        // E:\work\demo\project\nest-project\dist\images\
        join(__dirname, '../images/' + new Date().getTime() + '.jpg'),
      );
      // console.log('join', join(__dirname, '../images/'));
      ws.write(buffer);
    });
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.spiderService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateSpiderDto: UpdateSpiderDto) {
    return this.spiderService.update(+id, updateSpiderDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.spiderService.remove(+id);
  }
}
